import React from 'react'
import http from '../../utils/http';
import {startClock} from '../../utils/common';
import {VALIDPWD ,VALIDPHONE, VALIDCODE} from '../../utils/valid'
import { Form } from 'react-validify'
// import { Toast } from '../components/Toast';

const rules = {
  msgCode: ['required', `regex:${VALIDCODE.reg}`],
  password: ['required', `regex:${VALIDPWD.reg}`]
}
const errorMessages = {
  'required.account': VALIDPHONE.required,
  'regex.account': VALIDPHONE.errMsg,
  'required.msgCode': VALIDCODE.required,
  'regex.msgCode': VALIDCODE.errMsg,
  'required.password': VALIDPWD.required,
  'regex.password': VALIDPWD.errMsg
}
const placeholders = {
  account: '请输入手机号',
  password: '请输入密码',
  msgCode: '请输入短信验证码'
}
let phoneCache = {}
let codeCache = {}
let phoneMsg = ''
let codeMsg = ''
class ResetPwd extends React.Component {
  state = {
    password: '',
    account: '',
    msgCode:'',
    setPsw:'',
    setPhone: '',
    setCode:'',
    timePsw:'发送验证码',
    isabledPwd:true,
    pwdType: 'text',
    isCanclick:true,
    submitError: '',
    placeholders: {
      account: placeholders.account,
      password: placeholders.password,
      msgCode: placeholders.msgCode
    }
  }
  checkValid = (props) => {
    if(props.name==='account' || props.name==='msgCode') {
      this.setState({})
    }
  }
  // 校验组件
  Input = ({ error, onEnter, ...props }) => {
    // 异步
    if (props.name==='account' && props.value.length===11) {
      this.validphone(props)
    } else if (props.name==='msgCode' && props.value.length===4) {
      this.validCode(props)
    }
    return (
    <div>
      <input  autoComplete="off" {...props} style={{border: error 
        || (props.name==='msgCode' && props.value.length===4  && codeMsg)
        || (props.name==='account' && props.value.length===11 && phoneMsg) ? '1px solid #C13431': ''}} onBlur={(e)=>{
        props.onBlur(e);
        this.checkValid(props);
        const holders = this.state.placeholders
        holders[props.name] = placeholders[props.name]
        this.setState({
          placeholders: holders
        })
      }}/>
      {error ? <div className="error-msg">{error}</div> : ''}
      {props.name==='account' && props.value.length===11 && !error && phoneMsg?<div className="error-msg">{phoneMsg}</div>:''}
      {props.name==='msgCode' && props.value.length===4 && !error && codeMsg?<div className="error-msg">{codeMsg}</div>:''}
    </div>
  )};
  //校验验证码
  validCode = (props) => {
    let account = this.props.telphone;
    if (!account) {
      account = document.getElementById('reset-account').value;
      if (phoneMsg) return
    }
    if (props.name==='msgCode' && props.value.length === 4){
      if (!codeCache[props.value]) {
        http.get('/code/validate/msgCode',{
          params:{
            mobile: account,
            msgCode:props.value
          }
        })
        .then(data=> {
          if (data) {
            codeCache[props.value] = 1
            codeMsg = ''
          } else {
            codeCache[props.value] = 2
            codeMsg = '验证码输入错误'
          }
        }, err => {
        })
      } else if(codeCache[props.value]===1) {
        codeMsg = ''
      } else if(codeCache[props.value]===2) {
        codeMsg = '验证码输入错误'
      }
    }
  }
  //校验手机号
  validphone = (props) => {
    if (props.name==='account' && props.value.length === 11){
      if (!phoneCache[props.value]) {
        http.get('/register/isRegister',{
          params: {account: props.value}
        })
        .then(data=> {
          if (data) {
            phoneMsg = ''
            phoneCache[props.value] = 1
          } else {
            phoneMsg = '该手机号未注册'
            // this.setState({
            //   phoneMsg: '用户未注册'
            // })
            phoneCache[props.value] = 2
          } 
        }, err => {
          phoneCache[props.value] = 2
          if(err && err.code === 41003){
            phoneMsg = '该手机号未注册'
            // this.setState({
            //   phoneMsg: '用户未注册'
            // })
          }
        })
      } else if(phoneCache[props.value]===1) {
        phoneMsg = ''
        // this.setState({
        //   phoneMsg: ''
        // })
      } else if(phoneCache[props.value]===2) {
        phoneMsg = '该手机号未注册'
        // this.setState({
        //   phoneMsg: '用户未注册'
        // })
      }
    } 
  }
  componentDidMount(){
    phoneCache = {}
    codeCache = {}
    phoneMsg = ''
    codeMsg = ''
    if (this.props.type === '1') {
      delete rules.account
    } else {
      rules.account = ['required', `regex:${VALIDPHONE.reg}`]
    }
    this.setState({
      account: this.props.telphone
    })
  }
  // 发送验证码
  getCode = () => {
    let account = this.props.telphone;
    if (!account) {
      account = document.getElementById('reset-account').value;
      if (phoneMsg) return
    }
    const data = {
      type: 2,
      account,
    }
    http.post('/code/send/msgCode', data)
    .then(data => {
      if(data){
        this.setState({
          isabledPwd:false
        })
      }
    }, err => {
      this.setState({
        isabledPwd:true
      })
    })
  }
  // 修改密码
  resetpwd = values => {
    debugger
    // 修改
    if (this.props.telphone) {
      values.account = this.props.telphone
    } else { // 找回
      if (phoneMsg) return
    }
    if (codeMsg) return
    this.setState({
        isCanclick:false    
    })
    const data = {
      account: values.account,
      msgCode: values.msgCode,
      password: values.password
    }
    http.post('/back/password', data)
    .then(data=> {
      this.setState({
        isCanclick:true
      })
      if(data){
        // Toast('修改成功!')
        this.props.ShowInfo();
      }
    }, err => {
      this.setState({
        isCanclick:true
      })
    })
  }
  clearHolder = (name) => {
    const holder = this.state.placeholders
    holder[name] = ''
    this.setState({placeholders: holder})
  }
  clearError = () => {
    this.setState({
      submitError: '',
    })
  }
  render () {
    return (
      <Form
        rules={rules}
        errorMessages={errorMessages}
        className="form-horizontal reset-pwd">
        {this.props.telphone?
        <div className="form-group edit-filed-item re-form-text">
          <span className="col-md-2" style={{paddingRight:0,width:"80px"}}>手机号</span>
          <span className="col-md-10 edit-filed-tel" style={{paddingLeft:0}}>{this.props.telphone}</span>
        </div>
        :
        <div className="re-filed-item">
            <div className="re-form-text">手机号</div>
              <this.Input 
                type="text"
                id="reset-account"
                name="account"
                placeholder={this.state.placeholders.account}
                onFocus={()=>{
                  this.clearHolder('account')
                }}
                errmsg = {this.state.phoneMsg || ''}
                className="input-form"/>
        </div>
        }
        <div className="register-code">
          <div className="col-md-6 row col-xs-12">
            <this.Input 
              type="text"
              name="msgCode"
              placeholder={this.state.placeholders.msgCode}
              onFocus={()=>{
                this.clearError()
                this.clearHolder('msgCode')
              }}
              className="input-form"/>
          </div>                                             
          <div className="col-md-6 col-xs-12">
              <button className="register-codebtn col-md-12 col-xs-12" disabled={!this.state.isabledPwd?'disabled':''} onClick={event=>{
                event.preventDefault()
                this.setState({})
                let actel = document.getElementById('reset-account')?document.getElementById('reset-account').value:'';
                if((!phoneMsg&&this.props.telphone)||(!phoneMsg&&actel)){
                    this.setState({
                    isabledPwd:false
                  })
                  startClock(true,60,(data)=>{
                    this.setState({
                        timePsw:data
                    })
                    if(this.state.timePsw==='发送验证码'){
                        this.setState({
                            isabledPwd:true
                        })
                    }
                  })
                  this.getCode()
              }}}>
              {this.state.timePsw}</button>
          </div>
        </div>
        <div className="re-filed-item">
          <div className="re-form-text">密码</div>
          <this.Input type={this.state.textType} name="password" placeholder={this.state.placeholders.password} onFocus={()=>{
            this.setState({
              textType:'password'
            })
            this.clearHolder('password')
          }}
          className="input-form"/>
        </div>
        <div submit className="reset-btn" onClick = {(values)=>{this.resetpwd(values);}}>
          <input
            type="button"
            className="re-login-btn"
            value="完成"
            />
        </div>
      </Form>
    )
  }
}
export default ResetPwd